package advance.app.utils;

import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author : fafa
 * @version V1.0
 * @Project: demo
 * @Package advance.app.utils
 * @Description: TODO
 * @date Date : 2019年11月19日 15:44
 */
public class FileUpload {

    public static final String FILE_TYPE = "*";
    public static final String PATH_SEPARATOR = File.pathSeparator;
    public static final String SEPARATOR = File.separator;
    private static final Logger logger = LoggerFactory.getLogger(FileUpload.class);
    public static final String FILE_SPE = "#";
    public static final String CHAR_ALT = "@";
    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
    public static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");


    public static String nowTime(){
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(d).toString();
    }

    /**
     * @function 单文件上传
     * @return
     */
    public static Map<String,String> fileOne(MultipartFile file, String saveUrl, String fileType){
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));

        //String fileName = UUID.randomUUID() + suffix;
        //String fileName = file.getOriginalFilename();
        Map<String,String> map = new HashMap<>();
        //String[] strs = fileName.split("_");
        String newUrl = saveUrl+SEPARATOR+fileName+FILE_SPE+FileUpload.nowTime()+CHAR_ALT+UUID.randomUUID()+suffix;
        //map.put("type",strs[0].toUpperCase());
        //map.put("fname",strs[1]);
        //map.put("version",strs[2].toUpperCase());
        map.put("fpath",newUrl);
        map.put("suffix",suffix);
        System.out.println("文件路径：" + newUrl);
        String[] type_array = fileType.split(",");
        System.out.println("type: "+type_array.length);
        File saveFile = new File(newUrl);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return map;
    }

    /**
     * 在basePath下保存上传的文件夹
     * @param basePath
     * @param files
     */
    public static Map<String,String> saveMultiFile(String basePath, MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return null;
        }
        Map<String,String> map = new HashMap<>();
        try {
            if (basePath.endsWith("/")) {
                basePath = basePath.substring(0, basePath.length() - 1);
            }
            StringBuilder sb = new StringBuilder("");
            sb.setLength(0);
            for (MultipartFile file : files) {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));

                String filePath = basePath + "/" + fileName+CHAR_ALT+UUID.randomUUID()+suffix;
                makeDir(filePath);
                File dest = new File(filePath);
                try {
                    file.transferTo(dest);
                    sb.append(filePath).append(";");
                } catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                    return null;
                }
            }
            sb.deleteCharAt(sb.length()-1);
            map.put("path",sb.toString());
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 确保目录存在，不存在则创建
     * @param filePath
     */
    private static void makeDir(String filePath) {
        if (filePath.lastIndexOf('/') > 0) {
            String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
    }

    public static boolean moveFile(String srcPath,String destPath){
        try {
            logger.debug("moveFile from "+srcPath+" To "+destPath);
            if(new File(destPath).exists()){
                FileUtils.forceDelete(new File(destPath));
            }
            FileUtils.moveFile(new File(srcPath),new File(destPath));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean copyFile(String srcPath,String destPath){
        try {
            logger.debug("copyFile from "+srcPath+" To "+destPath);
            if(new File(destPath).exists()){
                FileUtils.forceDelete(new File(destPath));
            }
            FileUtils.copyFile(new File(srcPath),new File(destPath));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 备份数据
     * @param srcPath
     * @param backUpPath
     * @return
     */
    public static boolean copyDirectoryToDirectory(String srcPath,String backUpPath){
        try {
            logger.debug("copyFile from "+srcPath+" To backUpPath->"+backUpPath);
            FileUtils.copyDirectoryToDirectory(new File(srcPath),new File(backUpPath));
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean moveDirectoryToDirectory(String srcPath,String backUpPath){
        try {
            logger.debug("copyFile from "+srcPath+" To backUpPath --> "+backUpPath);
            FileUtils.moveDirectoryToDirectory(new File(srcPath),new File(backUpPath),true);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 修改CSV文件
     * @param fullFilePath
     * @param area
     * @param newVersion
     * @param updDttm
     * @return
     */
    public static boolean writeCsv(String fullFilePath, String type, String newVersion, String updDttm){
        // String filePath = "/Users/fafa/WorkFile/TestWise/MESProductList2.csv";
        try {
            // 创建CSV读对象
            CsvReader csvReader = new CsvReader(fullFilePath);
            CsvWriter csvWriter = new CsvWriter(fullFilePath,',', Charset.forName("GBK"));
            Map<String,String[]> map = new LinkedHashMap<>();
            // 读表头
            csvReader.readHeaders();
            map.put("HEAD",csvReader.getHeaders());
            while (csvReader.readRecord()){
                // 读一整行
                map.put(csvReader.get(0),csvReader.getValues());
            }
            csvReader.close();

            for (Map.Entry<String,String[]> entry : map.entrySet()){
                if(entry.getKey().equals(type)){
                    entry.getValue()[4] = newVersion;
                    entry.getValue()[5] = updDttm;
                }
            }

            for (Map.Entry<String,String[]> entry : map.entrySet()){
                csvWriter.writeRecord(entry.getValue());
                //System.out.println(entry.getKey()+"-->"+entry.getValue());
            }
            csvWriter.close();
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
